<?php
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Input;

class SNSController extends CenterController {
    protected $layout = 'layouts.master';

    public function getSNSgroup($groupId){
    	$sns_group = App::make('SNSGroup')->find($groupId);
    	if(!$sns_group){
    		return $this->makeView('errors.404','该圈子不存在',404);
    	}
    	return $sns_group;
    }
    
    /**
     * 测试用户是否圈子的管理者
     */
    public function isAdmin($group_id){
    	$member = App::make('SNSGroupMember')->where('user_id',Auth::user()->id)->where('group_id', $group_id)->first();
    	if ($member && $member->is_admin) {
    		return true;
    	} else {
    		return false;
    	}
    }
    
    /**
     * 测试用户是否圈子的创建者
     * 
     *@param $group_id 圈子id
     *@param $user_id  检测的用户的id
     */
    public function isCreator($group_id, $user_id){
    	$member = App::make('SNSGroupMember')->where('user_id',$user_id)->where('group_id', $group_id)->first();
    	if ($member && $member->is_creator) {
    		return true;
    	} else {
    		return false;
    	}
    }
    
    /**
     * 创建圈子
     */
    public function create()
    {
        $page = Input::get('page', 1);
        $rows_per_page = Input::get('rows_per_page', PaginationHelper::ROWS_PER_PAGE);
		$offset = ($page-1) * $rows_per_page;
		$city_id = Input::get('city_id', null);
		$cat_id = Input::get('cat_id', null);
		$exclude = Input::get('exclude', '');
		if(!is_array($exclude)){
			$exclude = explode(',', $exclude);
		}
		$experience = Input::get('experience', null);
		$cond = [
			'city' => $city_id,
			'cat_id' => $cat_id,
			'experience' => $experience,
		];
        $q = Input::get('q', null);
		//$fans = Follow::followerList($q, $rows_per_page, $offset, $exclude, $cond);
		$fans = Lawyer::getLawyerList($q, $rows_per_page, $offset, $exclude, $cond);
		$fans_array = $fans->toArray();
		foreach($fans_array as &$fans_item) {
			$fans_item['avatar'] = UtilsHelper::getImage($fans_item['avatar'], "img/dfimg.png");
		}
    	return $this->makeView('group.create',$fans_array);
    }   
    
    /**
	 * 保存创建的圈子
     */
    public function store()
    {
    	$data = Input::all();
    	$rules  = array(
    			'group_name'    => 'required|unique:sns_group,group_name,NULL,NULL|between:1,15',
    			'group_avatar'	=> 'required'
    	);
    	$messages = array(
    			'group_name.required'      => '请输入群名',
    			'group_avatar.required'      => '请输入群头像',
    			'group_name.unique'      => '该群名已被使用',
    			'group_name.between'      => '群的名字不能超过15个字',
    	);
    	$validator = Validator::make($data, $rules, $messages);
    	if ($validator->fails()) {
    		return $this->makeView(
    				'errors.400',
    				$validator->errors(),
    				400
    		);
    	}
    	$members =array();
    	if (isset($data['members']) && is_array($data['members'])) {
	    	while(list($key,$val) = each($data['members'])){
				if( User::find($val) && ($val != Auth::user()->id)) $members[] = $val;	
	    	}
    	}
    	$option['groupname'] =$data['group_name'];					//群组名称,此属性为必须的
    	$option['desc'] ='律团';										//群组描述,此属性为必须的
    	$option['public'] = false;									//是否是公开群,此属性为必须的 true or false
    	$option['approval'] = false;								//加入公开群是否需要批准,没有这个属性的话默认是true, 此属性为可选的
    	$option['owner'] =(string)Auth::user()->id;					//群组的管理员,此属性为必须的
    	$option['members'] = $members;								//群组成员,此属性为可选的
    	try{
    		$result = new Easemob();    	       		
    		$groupJson = $result->createGroups($option);   		
    		$group = json_decode($groupJson);
    		if(isset($group->data->groupid)){
    			$sns_group = App::make('SNSGroup');
    			$sns_group->group_name   = $data['group_name'];
    			$sns_group->created_by   = Auth::user()->id;
    			$sns_group->post_count   = 0;
    			$sns_group->group_avatar = $data['group_avatar'];//?UploadHelper::preprocessUploadFilePath($data['group_avatar']):"img/succreturn-logo.png";
    			$sns_group->easemob_id  =  $group->data->groupid;
    		    if (Auth::user()->user_group_id == 1) {
	    			$sns_group->fans_cnt = 1;
	    			$sns_group->lawyers_cnt = 0;
	    		} else if (Auth::user()->user_group_id == 2) {
	    			$sns_group->lawyers_cnt = 1;
	    			$sns_group->fans_cnt = 0;
	    		}
	    		$sns_group->is_recommended = 1;
	    		// 创建者自动关注该圈子，并成为管理员
	    		$sns_group_member = App::make('SNSGroupMember');
	    		DB::transaction(function() use($sns_group_member, $sns_group,$members){
	    			$sns_group->save();
	    			$sns_group_member->group_id = $sns_group->id;
	    			$sns_group_member->user_id = Auth::user()->id;
	    			$sns_group_member->is_admin = 1;
	    			$sns_group_member->is_creator = 1;
	    			$sns_group_member->is_passed = 1;
	    			$sns_group_member->save();
	    			while(list($key,$val) = each($members)){
	    				SNSGroupMember::addGroupMember($sns_group->id, $val);
	    			}
	    		});
    		}else{
    		    Log::error(__METHOD__ . __LINE__ . $groupJson);
    			return $this->makeView('errors.503','创建失败，请重试',503);
    		}
    	} catch (Exception $ex) {
    		Log::error($ex);
    		return $this->makeView('errors.503','创建失败，请重试',503);
    	}
    	$sns_group->member_cnt = $sns_group->fans_cnt+$sns_group->lawyers_cnt;
    	return $this->makeView('group.edit', $sns_group->toArray());
    }
    


	/**
	 * 我的的圈子的列表
	 */
	public function mine()
    {
		$input = Input::all();
		$page = isset($input['page']) ? intval($input['page']) : 1;
		$order_by = isset($input['order_by']) ? $input['order_by'] : 'sns_group_member.updated_at';
		$keyword = isset($input['keyword']) ? $input['keyword'] : '';
		$page_row = Config::get('app.page_row');			
		$query = DB::table('sns_group_member')
			->leftJoin('sns_group', 'sns_group_member.group_id', '=', 'sns_group.id')
			->where('sns_group_member.user_id', Auth::user()->id);
			// ->where('sns_group_member.is_passed',1);

		if($keyword) {
			$query->where('group_name', 'like', '%'.$keyword.'%');
		}
		$count = $query->count();
		$offset = ($page-1)*$page_row;
		try{
				// 读数据
			$datas = $query->orderBy($order_by, 'DESC')->skip($offset)->take($page_row)->get();
			$dataArr = array();
			foreach($datas AS $data)
			{
				$dataArr[] = array(
					'group_id' => $data->id,	
					'group_name' => $data->group_name,	
					'group_avatar' => UtilsHelper::getImage($data->group_avatar, "img/dfimg.png"),
					'member_cnt' => $data->lawyers_cnt + $data->fans_cnt,	
					'last_msg' => $data->last_msg,
					'unread_msg_count' => $data->unread_count,
					'group_intro' => $data->group_intro,
					'created_at' => $data->created_at,
					'updated_at' => $data->updated_at,
					'easemob_id' => $data->easemob_id
//					'post_count' => $data->post_count
				);
			}

		}catch (Exception $ex) {
			Log::error($ex);
			return $this->makeView(
					'errors.503',
					'查看失败，请重试',
					503					
				);				
			}
		return $this->makeView('group.main',$dataArr);
    }


	/**
	* 设置圈子
	*/		
	public function edit($groupId)
	{
		$sns_group = $this->getSNSgroup($groupId);
		if($sns_group->created_by != Auth::user()->id){
			return $this->makeView(
				'errors.401',
				'您没有权限设置该圈子',
					401	
				);
		}
		if (Input::server ( 'REQUEST_METHOD' ) == 'POST') 
		{				
			$post = Input::all();
			$group_name = $post['group_name'];

			// 如果圈子名字变了的话，验证圈子名字没有已经被使用
			if ($sns_group->group_name != $group_name) {
				$rules  = array(
					'group_name' => 'unique:sns_group,group_name,NULL,NULL'
				);
				$messages = array(
					'group_name.unique'      => '该名已被使用',
				);				
				$validator = Validator::make($post, $rules, $messages);
				if ($validator->fails()) {
					return $this->makeView(
							'errors.400',
							$validator->errors(),
							400 
						);
				}
			}
			try {
				//修改圈子名称
				if(!empty($post['group_name']))
				{
					$sns_group->group_name =  $post['group_name'];
				}
				if(!empty($post['group_avatar']))
				{
					$sns_group->group_avatar = UploadHelper::preprocessUploadFilePath($post['group_avatar']);
				}
				$option['groupname'] = $sns_group->group_name; 	//群组名称,此属性为必须的
				$option['description'] = '律团'; 					//群组描述,此属性为必须的
				$group_id = $sns_group->easemob_id;				
				$result = new Easemob();
				$group = $result->setGroups($option,$group_id);
				$group = json_decode($group);
				if(isset($group->data->groupname)){
					$sns_group->save();	
				}								
			} catch (Exception $ex) {
				Log::error($ex);
				return $this->makeView(
						'errors.503',
						'设置失败，请重试',
						503 );
			}
			return $this->makeView(
	           	 	'general.200', 
	           		$sns_group->toArray(),
	            	200
	       		);
																			
			}else{				
				$sns_group = App::make('SNSGroup')->find($id);				
				$this->makeView( 'group.edit',$sns_group );				
			}
		}
		
		/**
		 * ajax上传图片
		 * @param string $field_name
		 */
		public function upload_image()
		{
			$field_name='group_avatar';
			$type_arr=explode('.', $_FILES['group_avatar']['name']);
			$type=end($type_arr);
			$allow_exts = ['jpg','jpeg','jpe','png','gif','bmp'];
			if(!in_array( strtolower($type), $allow_exts)){
				return $this->makeView(
						'errors.400',
						'图片格式不正确'	,
						400
					);
			}

			$group_avatar_folder = Config::get('app.upload_dir').'/group_img';
	        $upload_folder = UploadHelper::getFileFolder($group_avatar_folder);

			try{
				$upload_result  = UploadHelper::uploadImage($field_name, $upload_folder);
// 				if ($upload_result['error'] == 0){		
// 					for ($i=0; $i<count($upload_result['files']); $i++){				
// 						$sns_group = App::make('SNSGroup')->find($id);
// 						$sns_group->group_avatar = $upload_result['files'][$i]['path'];
// 						$sns_group->save();
// 					}		
// 				}
			}catch (Exception $ex) {
				Log::error($ex);
				return $this->makeView(
						'errors.503',
						'上传失败，请稍后再试。',
						503
				);
			}

			$group_avatar_path = $group_avatar_folder . "/" . $upload_result['files'][0]['basename'] . "." . $upload_result['files'][0]['ext'];
        	$file_url = route('file.show_image') . "?path=" . $group_avatar_path;
			return $this->makeView(
				'general.200',
            	array('file_path' => $group_avatar_path, 'file_url' => $file_url),
				200
			);
		}
		
		/**
		 * 圈子聊天内页
		 */
		public function chat($id){
			try{
				$sns_group = $this->getSNSgroup($id);
				$sns_group_member = App::make('SNSGroupMember')
				->leftjoin('user', 'sns_group_member.user_id', '=', 'user.id')
				->select(
						'user.realname',
						'user.avatar',
						'sns_group_member.user_id',
						'sns_group_member.is_admin',
						'sns_group_member.is_creator')
				->where('group_id', $id)->get();
				$sns_group->member_cnt = $sns_group->fans_cnt+$sns_group->lawyers_cnt;
				$sns_group->members = $sns_group_member;
				$sns_group->user_id = Auth::user()->id;
				// 设置及时通信的密码
				$sns_group->pwd = Easemob::getPass(Auth::user());
			}catch (Exception $ex) {
				Log::error($ex);
				return $this->makeView(
						'errors.503',
						'服务器暂时无法响应。请过一段时间以后再试',
						503
				);
			}
			$sns_group_array = $sns_group->toArray();
			$sns_group_array['group_avatar'] = UtilsHelper::getImage($sns_group_array['group_avatar'], "img/dfimg.png");
			foreach($sns_group_array['members'] as $key => &$member) {
				$member['avatar'] = UtilsHelper::getImage($member['avatar'], "img/dfimg.png");
			}

			$sns_group_array['is_admin'] = $this->isAdmin($id);
			$sns_group_array['is_creator'] = $this->isCreator($id, Auth::user()->id);

			// 归零此用户的未读消息数
			$current_group_member = App::make('SNSGroupMember')
				->where('group_id', $id)
				->where('user_id', Auth::user()->id)
				->first();
			$current_group_member->unread_count = 0;
			$current_group_member->save();

			return $this->makeView(
					'easemob.group_view',
					$sns_group_array,
					200
			);
		}
		
		/**
		 * 罗列圈子已有的成员
		 * 
		 * @param integer $id 圈子的id
		 */
	    public function listMembers($id)
	    {
            $page = Input::get('page', 1);
            $rows_per_page = Input::get('rows_per_page', PaginationHelper::ROWS_PER_PAGE);
    		$offset = ($page-1) * $rows_per_page;
    		$q = Input::get('q', null);
    		
            $query = SNSGroupMember::leftjoin('sns_group', 'sns_group.id', '=', 'sns_group_member.group_id')
                ->leftjoin('user', 'sns_group_member.user_id', '=', 'user.id')
                ->select(
            	   'user.id',
            	   'user.realname',
            	   'user.avatar',
            	   'sns_group_member.is_admin',
            	   'sns_group_member.is_creator',
            	   'sns_group_member.created_at'
                )
                ->where('sns_group.id', $id)
                ->take($rows_per_page)
                ->skip($offset);
            	
            if ($q) {
                $query->where('user.realname', 'like', "%$q%");
            }
            
            $snsGroupMembers = $query->get();
	        $snsGroupMembersArr = $snsGroupMembers->toArray();
	        foreach($snsGroupMembersArr as &$snsGroupMemberArr) {
	            $snsGroupMemberArr['avatar'] = UtilsHelper::getImage($snsGroupMemberArr['avatar'], 'img/dfimg.png');
	        }
			return $this->makeView(
				'general.200',
				$snsGroupMembersArr,
				200
			);
	    }
		
		/**
		 * 圈子详细
		 */
		public function detail($id)
		{
			try{
				$sns_group = $this->getSNSgroup($id);
				$sns_group_member = App::make('SNSGroupMember')
					->leftjoin('user', 'sns_group_member.user_id', '=', 'user.id')
					->select(
							'user.realname',
							'user.avatar',
							'sns_group_member.user_id',
							'sns_group_member.is_admin',
							'sns_group_member.is_creator',
							'sns_group_member.created_at'
							)
					->where('group_id', $id)->get();
    			$sns_group->member_cnt = $sns_group->fans_cnt+$sns_group->lawyers_cnt;
// 				$sns_group->members = $sns_group_member;
				$sns_group->is_mine = false;
				if($sns_group->created_by == Auth::user()->id){
					$sns_group->is_mine = true;
				}
			}catch (Exception $ex) {
				Log::error($ex);
				return $this->makeView(
						'errors.503',
						'服务器暂时无法响应。请过一段时间以后再试',
						503
				);
			}
			$sns_group_array = $sns_group->toArray();
			$sns_group_array['members'] = $sns_group_member->toArray();
			$sns_group_array['group_avatar'] = UtilsHelper::getImage($sns_group_array['group_avatar'], "img/dfimg.png");
			foreach($sns_group_array['members'] as $key => &$member) {
				$member['avatar'] = UtilsHelper::getImage($member['avatar'], "img/dfimg.png");
			}
			return $this->makeView(
				'general.200',
				$sns_group_array,
				200
			);
		}

		/**
		 * 圈子管理员批量添加成员
		 */
		public function addMember($id)
		{
			$sns_group = $this->getSNSgroup($id);
			if (Input::server ( 'REQUEST_METHOD' ) == 'POST') {
				$members = Input::get('members');
				$newMembers = array();
				//过滤不存在的用户或者已存在该圈子的用户
				while(list($key,$val) = each($members)){
					$member = App::make('SNSGroupMember')->where('user_id',$val)->where('group_id', $id)->count()>0;
					$user = User::find($val);
					if(!$member && $user) $newMembers[] = $val;	
				}
			try{
				DB::transaction(function() use($sns_group,$newMembers){
					while(list($key,$val) = each($newMembers)){
						SNSGroupMember::addGroupMember($sns_group->id, $val);
					}
				});
			}catch (Exception $ex) {
				Log::error($ex);
				return $this->makeView('errors.503','请求失败，请稍后再试。',503);
			}
			//返回添加的用户的信息
			$members_info = User::whereIn('id',$newMembers)->select('id', 'avatar', 'realname')->get()->toArray();
			return $this->makeView('general.200',$members_info,200);
			}else{
                $page = Input::get('page', 1);
                $rows_per_page = Input::get('rows_per_page', PaginationHelper::ROWS_PER_PAGE);
        		$offset = ($page-1) * $rows_per_page;
        		$q = Input::get('q', null);
        		
				$sns_group_member = App::make('SNSGroupMember')->where('group_id', $id)->lists('user_id');
				$fans = Follow::followerList($q, $rows_per_page, $offset, $sns_group_member);
				$fans_array = $fans->toArray();
				foreach($fans_array as &$fans) {
					$fans['avatar'] = UtilsHelper::getImage($fans['avatar'], "img/dfimg.png");
				}
				return $this->makeView('general.200',$fans_array,200);		
			}
		}
		
		/**
		 * 圈子管理员删除多个成员
		 */
		public function removeMembers($group_id)
		{
			if(!$this->isAdmin($group_id)) {
				return $this->makeView('errors.401', '只有管理员才可以删除成员', 401);
			}
			
			$params = Input::all();
            $rules = array(
                'members' => 'required|array'
            );
            $messages = array(
                'members.required' => '请提交要删除的圈子成员',
                'members.array' => '圈子成员列表要是数组的格式'
            );
            $validator = Validator::make($params, $rules, $messages);
            if ($validator->fails()) {
                // the given data did not pass validation
                return $this->makeView('errors.400', $validator->errors(), 400);
            }
			
			$members = Input::get('members');
			$removeMembers = array();
			
			//过滤不存在的用户或者不存在该圈子的用户
			while(list($key,$val) = each($members)){
				$member = App::make('SNSGroupMember')->where('user_id',$val)->where('group_id', $group_id)->count()>0;
				$is_creator = $this->isCreator($group_id, $val);
				$user = User::find($val);
				if($member && $user && !$is_creator) $removeMembers[] = $val;	
			}

			$sns_group = $this->getSNSgroup($group_id);
			try{
				DB::transaction(function() use($sns_group,$removeMembers){
				    foreach ($removeMembers as $user_id) {
						$sns_group->save();
						$sns_group_member = App::make('SNSGroupMember')->where('user_id', $user_id)->where('group_id', $sns_group->id)->first();
						$sns_group_member->delete();
						$result = new Easemob();
						$group = $result->delGroupsUser($sns_group->easemob_id,$user_id);
				    }
				});
			}catch (Exception $ex) {
				Log::error($ex);
				return $this->makeView('errors.503','请求失败，请稍后再试。',503);
			}
			//返回添加的用户的信息
			return $this->makeView('general.201','删除成功',200);
		}
		
		/**
		 * 圈子管理员删除某个成员
		 */
		public function removeMember($group_id, $user_id)
		{
			if(!$this->isAdmin($group_id)) {
				return $this->makeView('errors.401', '只有管理员才可以删除成员', 401);
			}

			if($this->isCreator($group_id, $user_id)) {
				return $this->makeView('errors.401', '不能删除这个成员，因为他是圈子的创建者', 401);
			}

			$sns_group = $this->getSNSgroup($group_id);
				try{
					DB::transaction(function() use($sns_group,$user_id){
						if (User::find($user_id)->user_group_id == 1) {
							$sns_group->decrement('fans_cnt');
						} else if (User::find($user_id)->user_group_id == 2) {
							$sns_group->decrement('lawyers_cnt');
						}
						$sns_group->save();
						$sns_group_member = App::make('SNSGroupMember')->where('user_id', $user_id)->where('group_id', $group_id)->first();
						$sns_group_member->delete();
						$result = new Easemob();
						$group = $result->delGroupsUser($sns_group->easemob_id,$user_id);
						
					});
				}catch (Exception $ex) {
					Log::error($ex);
					return $this->makeView('errors.503','请求失败，请稍后再试。',503);
				}
				//返回添加的用户的信息
				return $this->makeView('general.201','删除成功',200);
		}
		
		/**
		 * 关注一个圈子
		 */		
		public function join($id)
		{
			try{
				$sns_group = $this->getSNSgroup($id);
				$sns_group_member = App::make('SNSGroupMember')
					->where('group_id', $id)
					->where('user_id', Auth::user()->id)
					->get();
				if($sns_group_member->count()){
					return $this->makeView('errors.400', '你已经是该圈子成员', 400);
				}
				SNSGroupMember::addGroupMember($id, Auth::user()->id);
			}catch (Exception $ex) {
				Log::error($ex);
				return $this->makeView('errors.503','请求失败，请稍后再试。',503);
			}
			return $this->makeView('general.200','加入成功',200);
		}
		
		/**
		 * 离开一个圈子
		 */
		public function quit($id)
		{
			try{
				$sns_group = $this->getSNSgroup($id);
				if($sns_group->created_by == Auth::user()->id){
					return $this->makeView('errors.401', '创建人只能解散该圈子', 401);
				}
				$sns_group_member = App::make('SNSGroupMember')
				->where('group_id', $id)
				->where('user_id', Auth::user()->id)
				->first();
				if(!is_object($sns_group_member)){
					return $this->makeView('errors.400', '你不是该圈子成员', 400 );
				}
				DB::transaction(function()use($sns_group_member, $sns_group){
					$sns_group_member->delete();
					if (Auth::user()->user_group_id == 1) {
						$sns_group->decrement('fans_cnt');
					} elseif (Auth::user()->user_group_id == 2) {
						$sns_group->decrement('lawyers_cnt');
					}
					$result = new Easemob();
					$group = $result->delGroupsUser($sns_group->easemob_id,Auth::user()->id);
				});
			}catch (Exception $ex) {
				Log::error($ex);
				return $this->makeView('errors.503','请求失败，请稍后再试。',503);
			}
			return $this->makeView('general.200','退出成功',200);
		}
		
		/*
		 * 解散圈子
		 */
		public function dissolution($groupId){
			$sns_group = $this->getSNSgroup($groupId);
			if($sns_group->created_by != Auth::user()->id){
				return $this->makeView('errors.401', '您没有权限解散该圈子', 401);
			}
			try{
				DB::transaction(function() use ($sns_group){				
					$sns_group_member = App::make('SNSGroupMember')->where('group_id',$sns_group->id)->delete();
					$sns_group->delete();
					$result = new Easemob();
					$group = $result->deleteGroups($sns_group->easemob_id);
				});
			}catch (Exception $ex){
				Log::error($ex);
				return $this->makeView('errors.503', '服务器暂时无法响应，请稍后再试', 503);
			}
			return $this->makeView('general.200','解散成功', 200);
					
		}
		
		public function index($id)
		{
			$sns_group = App::make('SNSGroup')->find($id);
			$sns_group_member = NULL;
			if(Auth::check())
			{
				$sns_group_member = App::make('SNSGroupMember')
				->where('group_id', $id)
				->where('user_id', Auth::user()->id)
				->first();
			}
		
			$posts = Post::getGroupPosts($id, Input::get('offset', 0), Input::get('limit', 50));
			foreach($posts AS $post)
			{
				$post_ids[] = $post->id;
			}
			$post_extras = $post_likes = array();
			if(isset($post_ids))
			{
				$extras = Post::getPostExtras($post_ids);
				foreach($extras AS $extra)
				{
					$post_extras[$extra->post_id] = $extra;
				}
				if(Auth::check())
				{
					$likes = Like::liked_by_post_ids($post_ids);
					foreach($likes AS $like)
					{
						$post_likes[$like->item_id] = $like;
					}
				}
		
				$pics = $this->getPostPics($post_ids);
		
		
			}
			$this->layout->content = View::make('group.index')->with(compact('sns_group', 'sns_group_member', 'posts', 'post_extras', 'post_likes', 'pics'));
		}
		
		public function getPostPics($post_ids)
		{
			$datas = App::make('PostAttach')->where('type', '=', 'image')->whereIn('post_id', $post_ids)->get();
			$pics = array();
			if($datas)
			{
				foreach($datas AS $data)
				{
					$pics[$data->post_id][]= array(
							'id' => $data->id,
							'src' => $data->src,
					);
				}
			}
			return $pics;
		}	

		/**
		 * 被推荐的圈子的列表
		 */
		public function recommend()
		{
			$input = Input::all();
			$page = isset($input['page']) ? intval($input['page']) : 1;
			$order_by = isset($input['order_by']) ? $input['order_by'] : 'created_at';
			$keyword = isset($input['keyword']) ? $input['keyword'] : '';
			if (!$keyword) {
				$keyword = isset($input['q']) ? $input['q'] : '';
			}
			$page_row = isset($input['rows_per_page']) ? $input['rows_per_page'] : Config::get('app.page_row');
			$groupIds = SNSGroupMember::where('user_id', Auth::user()->id)->lists('group_id');
			// 分页
			$query = DB::table('sns_group');
			$query->where('is_recommended', 1)->whereNotIn('id', $groupIds);			
			if($keyword)
			{
				$query->where('group_name', 'like', '%'.$keyword.'%');
			}
			$count = $query->count();
			$offset = ($page-1)*$page_row;
		
			// 读数据
			try {
				$datas = $query->orderBy($order_by, 'DESC')->skip($offset)->take($page_row)->get();
				
				$dataArr = array();
				foreach($datas AS $data)
				{
					$dataArr[] = array(
						'group_id' => $data->id,	
						'group_name' => $data->group_name,	
						'group_avatar' => UtilsHelper::getImage($data->group_avatar, "img/dfimg.png"),	
						'member_cnt' => $data->lawyers_cnt + $data->fans_cnt,	
						'group_intro' => $data->group_intro,
						'created_at' => $data->created_at,
						'updated_at' => $data->updated_at,
						//'post_count' => $data->post_count
					);
				}
			}catch (Exception $ex) {
				Log::error($ex);
				return $this->makeView(
						'errors.503',
						'查看失败，请重试',
						503					
				);				
			}
			return $this->makeView('group.recommend', $dataArr);
		}
		
		/**
		 * 修改圈子条目
		 */
	    public function edititem($id, $field_type, $field_name)
	    {
			$field = $field_name;
			$sns_group = App::make('SNSGroup')->find($id);    		
	    	$current_value =$sns_group->$field;
	    	if ( in_array($field_type, ['input','textarea','select','radio','checkbox','file','image','avatar','address', 'workscope']) ) {
	    		if ( Input::server('REQUEST_METHOD') == 'POST' ) {    			
	    			switch ($field_type){
	    				case 'avatar':
	    					$sns_group->$field = Input::get( str_replace('.','_',$field_name) );
	    					$upfiles = Input::get('upavator_his');
	    					foreach ($upfiles as $upfile){
	    						if ($upfile != $sns_group->$field ){
	    							@unlink( $upfile );
	    						}
	    					}
	    					break;
	    				case 'address':
	    					$sns_group->province = Input::get('province');
	    					$sns_group->city = Input::get('city');
	    					$sns_group->district = Input::get('district');
	    					break;
	    				case 'workscope':
	    					$sns_group->work_scope = implode(',', Input::get('work_scope'));
	    					break;
	    				default:
	    					$sns_group->$field = Input::get( str_replace('.','_',$field_name) );
	    					break;
	    			}    			
	    			$sns_group->save();    			
	    			return Redirect::route('group.setting', $sns_group->id);
	    		}else{
						$work_scope_list = array();
						if($field_type == 'workscope')
						{
								$work_scope_list = UtilsHelper::workScope();
								$sns_group->work_scope = explode(',', $sns_group->work_scope);
						}
	    			$this->layout->content = View::make('group.form.'.$field_type,['sns_group'=>$sns_group, 'value'=>$current_value ,'name'=>$field_name, 'work_scope_list'=>$work_scope_list]);
	    		}
	    	}
    	}

		 
		/**
		 * 修改圈子条目
		 */
	    public function viewitem($id, $field_type, $field_name)
	    {
			$sns_group = App::make('SNSGroup')->find($id);    		
			if($field_name == 'member' || $field_name == 'admin')
			{
				// 律团网
				$query = App::make('SNSGroupMember')
					->leftJoin('user', 'user.id','=', 'sns_group_member.user_id')
					->leftJoin('lawyer', 'lawyer.user_id', '=', 'user.id')
					->where('group_id', $id)
					->where('user_group_id', 2);

				if($field_name == 'admin')
				{
						$query->where('is_admin', 1);
				}
				$lawyers = $query->get();

				// 粉丝团
				$query = App::make('SNSGroupMember')
					->leftJoin('user', 'user.id', '=', 'sns_group_member.user_id')
					->leftJoin('customer', 'customer.user_id', '=', 'user.id')
					->where('group_id', $id)
					->where('user_group_id', 1);

				if($field_name == 'admin')
				{
						$query->where('is_admin', 1);
				}
				$fans = $query->get();

				$this->layout->content = View::make('group.viewform.'.$field_type,['sns_group'=>$sns_group, 'lawyers'=>$lawyers, 'fans'=>$fans]);

			} else {
			
				$field = $field_name;
    			$current_value = $sns_group->$field;
				$this->layout->content = View::make('group.viewform.'.$field_type,['sns_group'=>$sns_group, 'value'=>$current_value ,'name'=>$field_name]);
			}
   		}

   		/**
   		 * 获取圈子的聊天记录
   		 * 
   		 *@param $groupId
   		 */
   		public function chatRecords($groupId)
   		{
   			// 这个圈子要存在
	    	$sns_group = App::make('SNSGroup')->find($groupId);
	    	if(!$sns_group) {
	    		return $this->makeView('errors.404','该圈子不存在',404);
	    	}

	    	// 看看当前用户是否圈子的成员
	    	if(!$this->is_member($groupId)) {
	    		return $this->makeView('errors.401','不是圈子成员没有访问权限',401);
	    	}

   			// pagination
			$input = Input::all();
	        $page = Input::get('page', 1);
	        $rows_per_page = Input::get('rows_per_page', PaginationHelper::ROWS_PER_PAGE);

			$offset = ($page-1) * $rows_per_page;
			$order = Input::get('order', 'latest');
			$orderby = 'timestamp';
			$direction = 'DESC';

	        $result = App::make('SNSMsg')
	        	->where('chat_type', 'groupchat')
	        	->where('associate_id', $groupId)
	        	->take($rows_per_page)
	        	->skip($offset)
	        	->orderBy($orderby, $direction)
	        	->get();

			return $this->makeView(
				'general.200', 
				$result->toArray()
			);
   		}

		public function is_member($groupId)
		{
			if(Auth::check())
			{
				$sns_group_member = App::make('SNSGroupMember')
					->where('group_id', $groupId)
					->where('user_id', Auth::user()->id)
					->first();
				return $sns_group_member ? true : false;
			}
			return false;
		}	
}   	

   		

	    
	    
	    /**
	     * ajax上传图片
	     * @param string $field_name
	     */




		
	    /**
	     * 创建动态
	     */
/*	    public function createPost($id)
	    {
					$sns_group = App::make('SNSGroup')->find($id);
					if($this->is_member($id))
					{
						$me = Auth::user();
						$case_cats = UtilsHelper::workScope();
						$this->layout->content = View::make('group.createpost')->with(compact('case_cats', 'me', 'sns_group'));
					} else {
							return Redirect::route('group.index', $id);
					}
	    }
*/
	    /**
	     * 创建动态
	     */
/*	    public function storePost($id)
	    {
			if($this->is_member($id))
			{
				$new_post = Post::storeGroupPost($id, Input::all());
				$post_imgs = Input::get('postpics');
				if( count($post_imgs)){
					foreach ($post_imgs as $img){
						$pim = new PostAttach();
						$pim->post_id = $new_post->id;
						$pim->type = 'image';
						$pim->src = $img;
						$pim->save();
					}
				}
				return Redirect::route('group.index', $id);
			} else {
				return Redirect::route('group.index', $id);
			}
	    }
*/
	    /**
	     * 更新动态
	     */
/*		public function item($id)
		{
        	$post = Post::findOrFail($id);
				$is_member = $this->is_member($post->post_group_id);
				$sns_group = App::make('SNSGroup')->find($post->post_group_id);
				$is_collected = 0;
				if(Auth::check())
				{
						$is_collected = Collect::collected_post($post);
				}
        		$this->layout->content = View::make('group.item')->with(compact('post', 'sns_group', 'is_member', 'is_collected'));
		}

		
		public function remove_image()
		{
			$file = Input::get('img'); 
			if( file_exists($file) && strpos($file,Config::get('app.upload_dir'))===0 ){				
				ImageHelper::removeThumbs($file);
				@unlink($file);
			}
		}

	public function all()
    {
		$input = Input::all();
		$page = isset($input['page']) ? intval($input['page']) : 1;
		$order_by = isset($input['order_by']) ? $input['order_by'] : 'updated_at';
		$keyword = isset($input['keyword']) ? $input['keyword'] : '';
		$page_row = Config::get('app.page_row');

		$query = DB::table('sns_group');
		if($keyword)
		{
			$query->where('group_name', 'like', '%'.$keyword.'%');
		}

		$count = $query->count();
		$total_page = ceil($count/$page_row);
		if($page<1)$page = 1;
		if($page>$total_page)$page = $total_page;
		$offset = ($page-1)*$page_row;
		try{
			// 读数据
			$datas = $query->orderBy($order_by, 'DESC')->skip($offset)->take($page_row)->get();
			$dataArr = array();
			foreach($datas AS $data)
			{
				$dataArr[] = array(
					'group_id' => $data->id,	
					'group_name' => $data->group_name,	
					'group_avatar' => $data->group_avatar,	
					'member_cnt' => $data->lawyers_cnt + $data->fans_cnt,	
					'group_intro' => $data->group_intro,
					'created_at' => $data->created_at,
					'updated_at' => $data->updated_at,
					'post_count' => $data->post_count
				);
			}
		}catch (Exception $ex) {
			Log::error($ex);
			return $this->makeView(
				'errors.503',
				'查看失败，请重试',
				503		
			);
		}
		return $this->makeView('group.main', $dataArr);
	}
	
		    public function upload_image2($field_name='upimg')
	    {

	    		$upload_folder = Config::get('app.upload_dir').'/user_img/'.Auth::user()->id;
	    		$upload_result  = UploadHelper::uploadImage($field_name, $upload_folder); //
	    		//$upload_result1 = UploadHelper::upload($field_name, $upload_folder);
	    		if ($upload_result['error'] == 0){
	    			for ($i=0; $i<count($upload_result['files']); $i++){
	    				$upload_result['files'][$i]['url'] = asset($upload_result['files'][$i]['path']);
	    				$upload_result['files'][$i]['thumb'] = asset( ImageHelper::getThumb($upload_result['files'][$i]['path'], ImageHelper::SIZE_SMALL) );
	    			}
	    		}
	    		return Response::make( json_encode($upload_result) );
	    	
	    }
*/
		 
